from queue import Queue
from multiprocessing import Queue as ProcQueue
from typing import Optional
import time


class Debug:

    def __init__(self, Queues, timeSwitch: bool = False, debugName: str = 'System',
                 timeFormat: str = '%H:%M:%S', fileName=None, color=None):
        self.__stat = True
        self.__color = color
        self.__colorDict = {
            'black': 40, 'red': 41, 'green': 42, 'yellow': 43, 'blue': 44, 'purple': 45,
            'blue2': 46, 'white': 47
        }
        self.__styleDict = {
            'normal': 0, 'highlight': 1, 'underline': 4, 'flash': 5, 'reverse': 7, 'division': 8
        }
        if Queues is not None:
            self.debugName = debugName
            self.timeFormat = timeFormat
            self.__timeSwitch = timeSwitch
            self.__Q = Queues
            self.__fileName = fileName
            if self.__fileName is not None:
                with open(self.__fileName, "w+") as fp:
                    fp.write(f"===== [{debugName}] =====\n")
                    fp.close()
        else:
            self.__stat = False

    def pushInfo(self, strs, status: str = 'Info', style: str = 'normal'):
        if self.__stat:
            if not self.__timeSwitch:
                infoText = '[{}-{}]--> {}'.format(self.debugName, status, strs)
            else:
                infoText = '[{}-{}-{}]--> {}'.format(self.debugName,
                                                     time.strftime(self.timeFormat, time.localtime(time.time())),
                                                     status, strs)
            if self.__fileName is not None:
                with open(self.__fileName, "a+") as fp:
                    fp.write(infoText + '\n')
                    fp.close()
            if self.__color is None:
                backColor = 'm'
            else:
                backColor = str(self.__colorDict[self.__color]) + 'm'
            styleFont = self.__styleDict[style]
            if status == 'Debug':
                infoText = f"\033[{styleFont};32{backColor} {infoText} \033[0m"
            elif status == 'Error':
                infoText = f"\033[{styleFont};31{backColor} {infoText} \033[0m"
            elif status == 'Warning':
                infoText = f"\033[{styleFont};33{backColor} {infoText} \033[0m"
            elif status == 'Info':
                infoText = f"\033[{styleFont}:37{backColor} {infoText} \033[0m"
            # print(backColor)
            if not self.__Q.full():
                self.__Q.put(infoText)
            else:
                self.__Q.get()
                self.__Q.put(infoText)
            print(infoText)
        else:
            pass

    def getInfo(self):
        if self.__stat:
            if not self.__Q.empty():
                res = self.__Q.get()
                return res
            else:
                return None
        else:
            pass
